const http = require('http');
const { countTokens } = require('@anthropic-ai/tokenizer');

const PORT = 3020;

// 计算请求中的所有 tokens
function calculateInputTokens(data) {
  // 将整个请求对象序列化为 JSON 字符串
  // 这样可以包含所有的结构信息（包括 keys、格式等）
  const jsonString = JSON.stringify(data);

  return countTokens(jsonString);
}

const server = http.createServer((req, res) => {
  if (req.url === '/api/v1/messages/count_tokens' && req.method === 'POST') {
    let body = '';

    req.on('data', chunk => {
      body += chunk.toString();
    });

    req.on('end', () => {
      try {
        const requestData = JSON.parse(body);
        const inputTokens = calculateInputTokens(requestData);

        const result = {
          input_tokens: inputTokens,
          context_management: null
        };

        res.writeHead(200, { 'Content-Type': 'application/json' });
        res.end(JSON.stringify(result));
      } catch (error) {
        res.writeHead(500, { 'Content-Type': 'application/json' });
        res.end(JSON.stringify({ error: error.message }));
      }
    });
  } else {
    res.writeHead(404, { 'Content-Type': 'application/json' });
    res.end(JSON.stringify({ error: 'Not Found' }));
  }
});

server.listen(PORT, () => {
  console.log(`Token 计数服务运行在 http://localhost:${PORT}`);
  console.log(`接口地址: POST http://localhost:${PORT}/api/v1/messages/count_tokens`);
});